//
//  HRUserOrderDetailViewController.m
//  haierapp
//
//  Created by Xia Zhiyong on 14-8-15.
//  Copyright (c) 2014年 haier. All rights reserved.
//

#import "HRUserOrderDetailViewController.h"
#import "HRUserGoodsListTableViewCell.h"
#import "HRCancelOrderView.h"
#import "ActionSheet.h"
#import "HROrder.h"
#import "HROrderApplyCell.h"
#import "HRGoodsInfoViewController.h"

#import "HRPaysucceedViewController.h"
#import "HRPaymentManager.h"

#import "HROrderProgressViewController.h"

#import "HROrderApplyViewController.h"

#define HEIGHT_WITH_PROGRESS 170.f
#define HEIGHT_NO_PROGRESS 127.0f

@interface HRUserOrderDetailViewController (){
    HROrder *orderInfo;
    NSMutableArray *arrayProductList;
}

@end

@implementation HRUserOrderDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        arrayProductList = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (__CUR_IOS_VERSION >= __IPHONE_7_0)
    {
        self.edgesForExtendedLayout= UIRectEdgeNone;
    }
    self.navigationItem.title = @"订单详情";
   
    
    [self loadOrderDetail];
}

//获取订单详情数据
-(void)loadOrderDetail{
    [self showCustomLoadingHud:kLoading inView:nil];
    [HRInterfaceManager getOrderDetails:_orderNo completion:^(BOOL isSucceed, NSString *message, id data) {
        [self hideCustomLoadingHud];
        
        if (isSucceed) {
            orderInfo = (HROrder*)data;
            if (orderInfo) {
                [self configViews];
            }
        }else{
            [self showTextHUD:message];
        }
        
        //页面加载耗时
        [self analysisEnd:nil];
        
    }];
}

//页面数据填充
-(void)configViews{
    _lblOrderType.text = [NSString stringWithFormat:@"%@",orderInfo.orderStateText];
    _lblFreight.text = [NSString stringWithFormat:@"¥%@",orderInfo.freight];
    _lblOrderTotalPrice.text = [NSString stringWithFormat:@"¥ %@",orderInfo.orderAmount];
    
    
    if (orderInfo.productList && orderInfo.productList.count) {
        [arrayProductList addObjectsFromArray:orderInfo.productList];
        [_tableView reloadData];
    }
    
    if (_orderType == ORDER_TYPE_AFTERSALE_DEALING || _orderType == ORDER_TYPE_WAIT_COMMENT ||_orderType==ORDER_TYPE_CANCELED) {
        _viewBottom.hidden = YES;
        self.tableVerticalSpace.constant = 0;
    }else{
        HROrdeDetailFoot *footView = [[HROrdeDetailFoot alloc] initWithFrame:self.viewBottom.bounds orderType:_orderType];
        footView.delegate = self;
        if (_orderType == ORDER_TYPE_WAIT_FOR_PAY) {
            [footView showOrderAmount:orderInfo.orderAmount];
            
            if ([orderInfo.isActivity intValue]==ACTIVITY_TYPE_PRE_PAYMENT) {
                if ([orderInfo.orderStateText isEqualToString:ORDER_STATUS_UNPAID]) {
                    //付定金
                    [footView showOrderAmount:orderInfo.depositamount];
                }else if([orderInfo.orderStateText isEqualToString:ORDER_STATUS_PAID_DEPOSIT]){
                    //付尾款
                    [footView showOrderAmount:orderInfo.balanceamount];
                }
            }
        }
        [self.viewBottom addSubview:footView];
    }

    if ([orderInfo.isActivity intValue]==ACTIVITY_TYPE_PRE_PAYMENT) {
        if ([orderInfo.orderStateText isEqualToString:ORDER_STATUS_UNPAID]) {
            //付定金
            _lblOrderPriceTitle.text=@"订金金额（含运费）：";
            _lblOrderTotalPrice.text=[NSString stringWithFormat:@"¥%@",orderInfo.depositamount];
        }else if([orderInfo.orderStateText isEqualToString:ORDER_STATUS_PAID_DEPOSIT]){
            //付尾款
            _lblOrderPriceTitle.text=@"尾款金额（含运费）：";
            _lblOrderTotalPrice.text=[NSString stringWithFormat:@"¥%@",orderInfo.balanceamount];
        }
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
   
}

#pragma mark - UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return arrayProductList.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (_orderType == ORDER_TYPE_WAIT_FOR_PAY || _orderType == ORDER_TYPE_CANCELED || _orderType == ORDER_TYPE_CLOSED ) {
        return HEIGHT_NO_PROGRESS;
    }else{
        return HEIGHT_WITH_PROGRESS;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    BOOL hasProgress = YES;
    if (_orderType == ORDER_TYPE_WAIT_FOR_PAY || _orderType == ORDER_TYPE_CANCELED || _orderType == ORDER_TYPE_CLOSED){
        hasProgress = NO;
    }
    HROrderDetailHead *headView = [[HROrderDetailHead alloc] initWithProgress:hasProgress];
    headView.delegate = self;
    headView.lblName.text = [NSString stringWithFormat:@"收货人:%@",orderInfo.name?orderInfo.name:@""];
    headView.lblPhone.text = [NSString stringWithFormat:@"%@",orderInfo.phone?orderInfo.phone:@""];
    headView.lblAddress.text = [NSString stringWithFormat:@"%@",orderInfo.addr?orderInfo.addr:@""];
    if (hasProgress) {
        headView.lblStatus.text = orderInfo.postSate;
        switch (_orderType) {
            case ORDER_TYPE_WAIT_FOR_DELIVERY:{ //待发货显示支付时间
                headView.lblTime.text = orderInfo.subDate;
                break;
            }
            case ORDER_TYPE_WAIT_FOR_RECEIPT:{//待收货显示发货货时间
                headView.lblTime.text = orderInfo.fhDate?orderInfo.fhDate:@"";
                break;
            }
            case ORDER_TYPE_WAIT_COMMENT|ORDER_TYPE_REFUNDING:{ //待评论显示收货时间
                headView.lblTime.text = orderInfo.qrDate?orderInfo.qrDate:@"";
                break;
            }
            default:
                break;
        }
    }
    

    
    return headView;
}


-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"HRUserGoodsListTableViewCell";
    HROrderApplyCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[HROrderApplyCell alloc] init];
        [cell setShowBottomLine:YES];
    }
    if (_orderType == ORDER_TYPE_RECEIPTED || _orderType == ORDER_TYPE_SUCCEED) {
        [cell configWithData:[arrayProductList objectAtIndex:indexPath.row] showAfertSale:YES];
        cell.applyAfterSale = ^{ //申请售后
            HROrderApplyViewController *viewC = [[HROrderApplyViewController alloc] initWithNibName:@"HROrderApplyViewController" bundle:nil];
            viewC.applyType = APPLY_TYPE_AFTERSALE;
            orderInfo.orderId = orderInfo.orderNo;
            orderInfo.totalPrice = orderInfo.orderAmount;
            viewC.order = orderInfo;
            [self.navigationController pushViewController:viewC animated:YES];
        };
    }else{
       [cell configWithData:[arrayProductList objectAtIndex:indexPath.row]]; 
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    HROrderProductInfo *info = [arrayProductList objectAtIndex:indexPath.row];
    HRGoodsInfoViewController *viewC = [[HRGoodsInfoViewController alloc] initWithNibName:@"HRGoodsInfoViewController" bundle:nil];
    viewC.goodsId = [NSString stringWithFormat:@"%@", info.productId ];
    [self.navigationController pushViewController:viewC animated:YES];
}

#pragma mark - HROrderDetailHeadDelegate
//查看进度页面
-(void)pushToProgressView{
    HROrderProgressViewController *orderProgressViewController=[[HROrderProgressViewController alloc]initWithStyle:UITableViewStylePlain];
    
    orderProgressViewController.orderNo=_orderNo;//订单编号
    
    [self.navigationController pushViewController:orderProgressViewController animated:YES];

}

#pragma mark -HROrdeDetailFootDelegate

//再次购买
-(void)buyAgainOrderProduct{
    
}

//确认收货
-(void)receiveProducts{
    [self showCustomLoadingHud:kLoading inView:nil];
    
    [HRInterfaceManager receiptOrder:orderInfo.orderNo completion:^(BOOL isSucceed, NSString *message, id data) {
        
        [self hideCustomLoadingHud];
        
        if (isSucceed) {
            //确认收货成功
            [self showSuccessHud:@"已确认收货"];
            
            //重新加载订单数据
            [HRCommonData shareCommonData].hasNewOrder=YES;
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(HUD_DELAY_HIDE_SECOND * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
            
        }else{
            [self showTextHUD:message];
        }
        
    }];
}

//取消订单
-(void)cancelOrder{
    HRCancelOrderView *cancelOrderView = [[HRCancelOrderView alloc] init];
    cancelOrderView.orderNo=_orderNo;
    [cancelOrderView loadTable];
    
    ActionSheet* actionSheet =  [[ActionSheet alloc] initWithTitle:@"请选择取消订单的理由" delegate:self cancelButtonTitle:@"确定" viewCustom:cancelOrderView otherButtonTitles:nil];
    [actionSheet show];

}

//付款
-(void)paymentOrder{
    
    NSString *subject = @"";  //订单商品标题
    for (HROrderProductInfo *product in orderInfo.productList) {
        subject = [NSString stringWithFormat:@"%@ %@",subject,product.productTitle];
    }
    NSString *amount = orderInfo.orderAmount;   //订单价格
    
    if ([orderInfo.isActivity intValue]==ACTIVITY_TYPE_PRE_PAYMENT) {
        if ([orderInfo.orderStateText isEqualToString:ORDER_STATUS_UNPAID]) {
            //付定金
            amount=orderInfo.depositamount;
        }else if([orderInfo.orderStateText isEqualToString:ORDER_STATUS_PAID_DEPOSIT]){
            //付尾款
            amount=orderInfo.balanceamount;
        }
    }
    
    [HRPaymentManager paymentWithOrderId:_orderNo subject:subject body:@"暂无" amount:amount completion:^(BOOL isSucceed, NSString *message) {
        if (isSucceed) {
            //更改订单状态
            [HRCommonData shareCommonData].hasNewOrder=YES;
            //push到支付成功页面
            HRPaysucceedViewController *viewC = [[HRPaysucceedViewController alloc] initWithNibName:@"HRPaysucceedViewController" bundle:nil];
            viewC.pushType = PUSH_FROM_INFO ;
            [self.navigationController pushViewController:viewC animated:YES];
            
        }else{
            [self showTextHUD:message];
        }
    }];

}

#pragma mark - ActionSheet Delegate Methods
- (void)actionSheet:(ActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex==(-1)) {
        HRCancelOrderView *cancelOrderView=(HRCancelOrderView *)actionSheet.viewCustom;
        
        NSString *cancelReason=[cancelOrderView getCurrentSelectItem];
        NSString *orderNo=cancelOrderView.orderNo;
        
        //取消订单
        [self showCustomLoadingHud:kLoading inView:nil];
        [HRInterfaceManager cancelOrderById:orderNo andReason:cancelReason completion:^(BOOL isSucceed, NSString *message, id data) {
            [self hideCustomLoadingHud];
            
            if (isSucceed) {
                [self showSuccessHud:@"订单取消成功！"];
                //重新加载订单数据
                [HRCommonData shareCommonData].hasNewOrder=YES;
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(HUD_DELAY_HIDE_SECOND * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }else{
                [self showTextHUD:message];
            }
        }];
        
    }
}


@end
